<template>
  <el-select
    :model-value="modelValue"
    :placeholder="placeholder"
    :clearable="clearable"
    @change="$emit('update:modelValue', $event)"
  >
    <el-option
      v-for="data in dataList"
      :key="data.itemValue"
      :label="data.itemName"
      :value="Number(data.itemValue)"
    />
  </el-select>
</template>

<script setup>
import { ref, watch } from "vue";
import { useDictStoreHook } from "@/store/modules/dict";
import { getDictLabel } from "@/utils/dict";

defineOptions({
  name: "DictSelect"
});

// 传值
const props = defineProps({
  modelValue: {
    required: true
  },
  dictType: {
    type: String,
    required: true
  },
  clearable: {
    type: Boolean,
    required: false,
    default: () => false
  },
  placeholder: {
    type: String,
    required: false,
    default: () => "请选择"
  }
});

const dataList = ref([]);

watch(
  () => props.dictType,
  async newValue => {
    if (!newValue) return false;

    const params = {
      pageNum: 1,
      pageSize: 999
    };

    const dictList = JSON.parse(localStorage.getItem("dictList")) || [];

    if (dictList.length > 0) {
      dataList.value = getDictLabel(dictList, newValue);
    } else {
      const { data } = await useDictStoreHook().getDictlist(params);
      dataList.value = getDictLabel(data.records, newValue);
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped></style>
